<?php
// +----------------------------------------------------------------------
// | HkCms 文章模型
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\admin\model\cms;

use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class Archives extends Model
{
    use SoftDelete;

    /**
     * 软删除字段
     * @var string
     */
    protected $deleteTime = 'delete_time';

    public static $tablename;

    /**
     * 指定自动时间戳类型
     * @var string
     */
    protected $autoWriteTimestamp = 'int';

    /**
     * 格式化发布日期
     * @param $value
     * @param $data
     * @return false|string
     */
    public function getPublishTimeTextAttr($value, $data)
    {
        return empty($data['publish_time']) ? '-' : date('Y-m-d H:i:s', $data['publish_time']);
    }

    /**
     * 格式化url
     * @param $value
     * @param $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        if (empty($value)) {

            $info = Category::where(['id'=>$data['category_id']])->find();
            if ($info) {
                if ($data['status']!='normal') {
                    // 去到预览页
                    return (string) url('/cms.archives/preview',['category_id'=>$data['category_id'],'id'=>$data['id']]);
                }

                $mode = site('url_mode');
                if ($mode==1 || app()->http->getName()!='index') { // 动态
                    $value = index_url('/index/show', ['list'=>$info['name'],'id'=>$data['id']]);
                } else if ($mode==2) { // /父目录/目录/内容id.html
                    if ($info['parent_id']) {
                        $name = Category::where(['id'=>$info['parent_id']])->value('name');
                        $value = '/'.$name.'/'.$info['name'].'/'.$data['id'].'.html';
                    } else {
                        $value = '/'.$info['name'].'/'.$data['id'].'.html';
                    }
                } else if ($mode==4) { // /模型/栏目/内容ID.html
                    $tb = \app\admin\model\cms\Model::where(['id'=>$data['model_id']])->value('tablename');
                    $tb = strtolower($tb);
                    $value = '/'.$tb.'/'.$info['name'].'/'.$data['id'].'.html';
                } else if ($mode==5 || $mode==3) { // /目录/内容ID.html
                    $value = '/'.$info['name'].'/'.$data['id'].'.html';
                }
            }
        }
        return $value;
    }

    /**
     * 格式化
     * @param $value
     * @param $data
     * @return false|string
     */
    public function getDeleteTimeTextAttr($value, $data)
    {
        return empty($data['delete_time']) ? '-' : date('Y-m-d H:i:s', $data['delete_time']);
    }

    /**
     * save 方法下，新增，修改都会触发
     * @param Model $model
     * @return mixed|void
     */
    public static function onBeforeWrite($model)
    {
        $publishTime = $model->getData('publish_time');
        if (empty($publishTime)) {
            $model->setAttr('publish_time', time());
        } else if (!is_numeric($publishTime)) {
            $model->setAttr('publish_time', strtotime($publishTime));
        }
    }

    /**
     * 查询后，使用与模型->select()/find()后执行save，保证表名称保持一致。
     * @param Model $model
     */
    public static function onAfterRead(Model $model)
    {
        if (!empty(self::$tablename)) {
            $model->name = $model->getName() != self::$tablename ? self::$tablename:$model->getName();
        }
    }

    /**
     * 获取栏目对应的表格信息
     * @param $categoryId
     * @param $categoryInfo
     * @return array|Model|null
     */
    public function getTableInfo($categoryId, &$categoryInfo=null)
    {
        if (empty($categoryId)) {
            abort(404, lang('%s not null',['category_id']));
        }
        $categoryInfo = Category::where(['id'=>$categoryId,'status'=>'normal'])->find();
        if (empty($categoryInfo)) {
            abort(404, lang('Column information does not exist'));
        }
        $modelInfo = \app\admin\model\cms\Model::where(['status'=>'normal', 'id'=>$categoryInfo['model_id']])->find();
        if (empty($modelInfo)) {
            abort(404, lang('Model information does not exist'));
        }
        return $modelInfo;
    }

    /**
     * 无需表前缀, 定义表名称
     * @param $name
     * @return $this
     */
    public function setTable($name)
    {
        $this->name = $name;
        self::$tablename = $name;
        return $this;
    }

    /**
     * 固定方法，用于栏目删除后的处理
     * @param $modelInfo
     * @param $categoryId
     * @param int $force 1=分类放入回收站，2=还原，3=销毁
     */
    public function handleDel($modelInfo, $categoryId, $force=1)
    {
        if ($force==3) {
            $ids = \think\facade\Db::name($modelInfo['tablename'])->where(['category_id'=>$categoryId])->where('delete_time','not null')->column('id');
            \think\facade\Db::name($modelInfo['tablename'])->where(['category_id'=>$categoryId])->where('delete_time','not null')->delete();
            if ($modelInfo['type']=='more') {
                \think\facade\Db::name($modelInfo['tablename'].'_data')->whereIn('id',$ids)->delete();
            }
        } else if ($force == 2) {
            (new Archives)->onlyTrashed()->name($modelInfo['tablename'])->where(['category_id'=>$categoryId])->update(['delete_time'=>null]);
        } else {
            (new Archives)->setTable($modelInfo['tablename'])->where(['category_id'=>$categoryId])->update(['delete_time'=>time()]);
        }
    }

    /**
     * 获取列表，用于内容标签
     * @param $tag
     * @param $page \think\Paginator|mixed paginate 分页对象
     * @return array|mixed|object|\think\App
     */
    public function handleTag($tag, &$page)
    {
        $tag['order'] = !empty($tag['order']) ? $tag['order'] : 'weigh desc';
        $tag['num'] = intval($tag['num']);

        // 获取操作的表
        if (empty($tag['model']) || !is_numeric($tag['model'])) {
            $cateInfo = Category::where(['id'=>$tag['catid'],'status'=>'normal'])->find();
            if (empty($cateInfo['model_id'])) {
                return [];
            }
            $tag['model'] = $cateInfo['model_id'];
        }
        $modelInfo = \app\admin\model\cms\Model::where(['status'=>'normal','id'=>$tag['model']])->find();
        if (empty($modelInfo)) {
            return [];
        }

        $map = [['status','=','normal']];
        // 获取栏目ID，包含下级。
        if (!empty($tag['catid']) && is_numeric($tag['catid']) && $tag['insub']==1) {
            $catIdArr = Category::where(['status'=>'normal','model_id'=>$tag['model']])->where('parent_id','=', $tag['catid'])->column('id');
            if (!empty($catIdArr)) {
                $catIdArr[] = $tag['catid'];
                $map[] = ['category_id','in',$catIdArr];
            } else {
                $map[] = ['category_id','=',$tag['catid']];
            }
        } else if (!empty($tag['catid']) && is_numeric($tag['catid']) && $tag['insub']==0) {
            $map[] = ['category_id','=',$tag['catid']];
        }
        if ($tag['page']) { // 开启分页
            $param = \think\facade\Request::param();
            array_shift($param);
            $obj = $this->setTable($modelInfo->tablename)
                ->with(['category','model'])
                ->where($map)
                ->where($tag['where'])
                ->order($tag['order'])
                ->append(['publish_time_text','url'])
                ->paginate([
                'list_rows'=> $tag['num'],
                'var_page' => 'page',
                'query' => $param
            ], false);
            $array = $obj->toArray()['data'];
            $page = $obj;
            // $array['page_html'] = $obj->render();
        } else {
            $array = $this->setTable($modelInfo->tablename)->with(['category','model'])->where($map)->where($tag['where'])->order($tag['order'])->limit($tag['num'])->select();
        }

        // 是否显示副表
        if (!empty($tag['more']) && $tag['more']==1 && !empty($array)) {
            foreach ($array as $key=>$value) {
                $array[$key]['more'] = Db::name($modelInfo->tablename.'_data')->where(['id'=>$value['id']])->find();
            }
        }
        return $array;
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function model()
    {
        return $this->belongsTo(\app\admin\model\cms\Model::class);
    }
}